package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.question.domain.WrongRecord;
import com.wuwei.elearning.question.mapper.WrongRecordMapper;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import com.wuwei.elearning.vo.IdVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-04-01
 */
@RestController
@RequestMapping("/elearning/wrongRecord")
@CrossOrigin
public class WrongRecordController {

    @Resource
    private WrongRecordMapper wrongRecordMapper;

    /**
     * 更新数据库表中的错误记录
     * 1.先去查询数据库中该用户以前关于这道题是否有记录
     * 2，如果有记录，则执行更新
     * 3.如果无记录，则执行添加
     * @param idVo
     * @param request
     * @return
     */
    @PostMapping("addOrUpdate")
    public Result<String> addOrUpdate(@RequestBody IdVo idVo, HttpServletRequest request){
        List<Long> ids = idVo.getIds();
        Long selectedId = idVo.getSelectedId();
        //这里先对ids进行一个去重
        List<Long> deduplicatedList  = ids.stream().distinct().collect(Collectors.toList());
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        deduplicatedList.forEach(id->{
            LambdaQueryWrapper<WrongRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WrongRecord::getUserAccount,account).eq(WrongRecord::getQuestionId,id);
            WrongRecord wrongRecord = wrongRecordMapper.selectOne(queryWrapper);
            if (wrongRecord==null) {
                wrongRecord = new WrongRecord();
                wrongRecord.setCreatedTime(LocalDateTime.now());
                wrongRecord.setQuestionId(id);
                wrongRecord.setUserAccount(account);
                wrongRecord.setSelectedId(selectedId);
                wrongRecordMapper.insert(wrongRecord);
            } else {
                wrongRecord.setCreatedTime(LocalDateTime.now());
                wrongRecordMapper.updateById(wrongRecord);
            }
        });
        return Result.ok("错题更新成功！");
    }

    @DeleteMapping("deleteByQuestionId/{questionId}")
    public Result<String> deleteByQuestionId(@PathVariable("questionId") Long questionId, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        LambdaQueryWrapper<WrongRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongRecord::getQuestionId,questionId).eq(WrongRecord::getUserAccount,account);
        wrongRecordMapper.delete(queryWrapper);
        return Result.ok("错题删除成功！");
    }

}

